#coding='utf-8'
from requests import Request, Session
import time
from imp import reload
from urllib import request as urllib2
from lxml import etree
import pymysql
import json
import sys
reload(sys)
import requests
#通过球队页面获取队内所有球员,数据库
def get_one_page(url):
    response = requests.get(url)
    response.encoding = "utf-8"
    if response.status_code == 200:
        return response.text
    return None

def main():
    db = pymysql.connect(host='localhost', user='root', password='', port=3306, db='nbaData', charset='utf8')
    cursor = db.cursor()
    searchTeam_sql = 'select href, team from nbateam'
    insertPlayerInfo_sql = 'REPLACE INTO nbaplayer(id, player, now_team) VALUES (%s,%s, %s)'
    cursor.execute(searchTeam_sql)  # 执行查询
    data = cursor.fetchall()  # 获取查询到数据
    print(data)
    for row in data:
        print(row[0])
        url = 'http://www.stat-nba.com' + row[0]
        get_one_page(url)
        text = get_one_page(url)
        dom = etree.HTML(text)
        if dom is None:
            return
        node_list = dom.xpath('//table[@class="stat_box"]//tr[@class="sort"]')
        for node in node_list:
            player = node.xpath('./td[2]/a/text()')
            playerId = node.xpath('./td[2]/a/@href')[0].replace('/player/', '').replace('.html', '')
            print(player)
            print(playerId)
            cursor.execute(insertPlayerInfo_sql, (playerId,player, row[1] ))
            db.commit()
if __name__ == '__main__':
    main()